package cn.liukuan.jps.plugins;

import org.apache.lucene.analysis.TokenFilter;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.apache.lucene.analysis.tokenattributes.PositionIncrementAttribute;
import org.apache.lucene.util.AttributeSource;

import java.io.IOException;
import java.util.Map;
import java.util.Set;
import java.util.Stack;

/**
 * Created by liukuan on 16/6/3.
 */
public class IKSameFilter extends TokenFilter {

    private CharTermAttribute cta = null;
    private PositionIncrementAttribute pia = null;
    private AttributeSource.State current;
    private Stack<String> sames = null;
    private IKSynonymsCantiner sameCantiner = null;

    protected IKSameFilter(TokenStream input) {
        super(input);
        cta = this.addAttribute(CharTermAttribute.class);
        pia = this.addAttribute(PositionIncrementAttribute.class);
        sames = new Stack<String>();
        sameCantiner = IKSynonymsCantiner.getInstance();
    }

    @Override
    public final boolean incrementToken() throws IOException {
        if(sames.size()>0) {
            String str = sames.pop();
            restoreState(current);
            cta.setEmpty();
            cta.append(str);
            pia.setPositionIncrement(0);
            return true;
        }

        if(!this.input.incrementToken()) return false;

        if(addSames(cta.toString())) {
            current = captureState();
        }
        return true;
    }

    private boolean addSames(String name) {

        Map<String, Set<String>> synonysMap = sameCantiner.getSynonysMap();

        Set<String> strings = synonysMap.get(name);

        if(strings != null) {
            for(String str: strings) {
                sames.push(str);
            }
            return true;
        }
        return false;
    }
}
